<template>
  <view >
    <view class="search-box">
      <!-- 使用uni-ui 提供的搜索组件-->
      <uni-search-bar  @input="input"  @clear="clearKW" :radius="100" cancelButton="none" clearButton="auto" :focus="true"></uni-search-bar>
    </view>
    <!-- 建议搜索结构-->
    <view class="sugg-list" v-if="searchResults.length!==0">
        <view class="sugg-item" v-for="(item,index) in searchResults" :key="index" @click="gotoDetail(item.goods_id)">
          <view class="good-name">{{item.goods_name}}</view>
          <uni-icons type="arrowright" size="16"></uni-icons>
        </view>
    </view>
    <!-- 搜索历史-->
    <view class="history-box" v-else-if="historySearch.length!=0" >
      <!-- 标题区域-->
      <view class="history-title">
        <text>搜索历史</text>
        <uni-icons type="trash" size="17" @click="clearHistory"></uni-icons>
      </view>
      <!-- 列表区域  展示历史搜索记录-->
      <view class="history-list">
         <uni-tag :text="item" v-for="(item,index) in histories" :key="index" @click="clickHistory(item)"></uni-tag>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        //延时器的timerId
        timer:null,
        keywords:'',
        searchResults:[],//关键字搜索结果
        historySearch:[],//历史搜索
      }
    },
    onLoad() {
      this.historySearch = JSON.parse(uni.getStorageSync('kw')||'[]')
    },
    methods: {
      //输入事件
      input(val){
        //清除上一次的定时器
        clearTimeout(this.timer)
        this.timer = setTimeout(()=>{ 
           this.keywords=val
           this.getSearchList()
        },500)
      },
      //清除关键字 kw  提高客户体验
      clearKW(){
       this.searchResults = []
      },
      //获取关键字搜索的函数
      async getSearchList(){
        //判断关键字是否为空|空格
        if(this.keywords.trim() === ''){
           return this.searchResults = []
        }else{
          //发起请求
          const {data : res} = await uni.$http.get('/api/public/v1/goods/qsearch',{query:this.keywords})
          if(res.meta.status==200){
            this.searchResults = res.message
          }
        }
      },
      gotoDetail(goods_id){
        uni.navigateTo({
          url:'/subpkg/goods_detail/goods_detail?goods_id=' + goods_id
        })
        //点击了跳转的商品 才记录 搜索记录
          this.saveSearchHistory()
      },
      //保存搜索的记录关键字
      saveSearchHistory(){
          //this.historySearch.push(this.keywords)      
          const set = new Set(this.historySearch)
          //调用Set对象的 delete方法，移除对应元素
          set.delete(this.keywords)
          //调用Set对象的 add方法，向Set添加元素
          set.add(this.keywords)
          this.historySearch = Array.from(set)
          //本地持久化
          uni.setStorageSync('kw',JSON.stringify(this.historySearch))
      },
      //点击清除搜索记录
      clearHistory(){
        uni.showModal({
          content:'是否清空历史记录?',
          success:(res)=>{
            if(res.confirm){
              //清空 data中的数据
              this.historySearch = []
              //清空本地存储
              uni.setStorageSync('kw',[])
            }
          }
        })
      },
      //点击历史的信息
      clickHistory(item){
        //此时的item为 之前搜索过的关键字
        uni.navigateTo({
          url:'/subpkg/goods_list/goods_list?query=' + item
        })
      }
    },
    computed:{
      histories(){
        return [...this.historySearch].reverse()
      }
    }
  }
</script>

<style lang="scss">
  .search-box{
    position: sticky;
    top: 0;
    z-index: 999;
  }
.uni-searchbar{
  background-color: #c00000;
}

.sugg-list{
  padding:  0 5px;
  .sugg-item{
    font-size: 12px;
    padding: 13px 0;
    border-bottom: 1px solid #efefef;
    display: flex;
    align-items: center;
    justify-content: space-between;
    
    .good-name{
      white-space: nowrap; //文字不允许换行
      overflow: hidden;
      text-overflow: ellipsis; //文本移除用 ... 代替
      margin-right: 3px;
    }
  }
}

.history-box{
  padding: 0 5px;
  
  .history-title{
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 40px;
    font-size: 13px;
    border-bottom: 1px solid #efefef;
  }
  
  .history-list{
    display: flex;
    flex-wrap: wrap;
    
    .uni-tag{
      margin-top: 5px;
      margin-right: 5px;
    }
  }
}
</style>
